assert(PandaDKPMaster, "PandaDKPMaster not found!")

------------------------------
--      Are you local?      --
------------------------------
local PandaDKPMaster = PandaDKPMaster
local Awarding =
{
   AwardDkp = 0,
   AwardNotes = '',
   AwardPool = '',
   AwardList = {},
   OtherPlayers = {},
   IncludeRaid = true,
   UI = {},
}
PandaDKPMaster.Awarding = Awarding

local dewdrop = AceLibrary("Dewdrop-2.5")



function Awarding:Enable()
   Awarding:SetupUI()
end

function Awarding:UpdateAwardList()
   local temp = {}
   for player, included in pairs(Awarding.OtherPlayers) do
      if included then temp[player] = true end
   end
   
   if (Awarding.IncludeRaid) then
      for player, class in pairs(PandaDKPMaster.Players:RaidMembers()) do
         temp[player] = true
      end
   end
   
   local list = {}
   for player, _ in pairs(temp) do tinsert(list, player) end
   sort(list)
   
   Awarding.AwardList = list
end


function Awarding:InternalCreateAward(mob, dkp, pool)
   
   -- Figure out how much DKP each player gets
   Awarding:UpdateAwardList()
   dkp = tonumber(dkp)
   dkp = dkp / #(Awarding.AwardList)
   
   Awarding:ConfirmAward(dkp, pool, mob, Awarding.AwardList)
end


function Awarding:CreateAwardConfirmed(dkp, pool, notes, players)

   -- If we're including the raid, then let them know
   if (Awarding.IncludeRaid and UnitInRaid("player")) then
      SendChatMessage(string.format("Awarding all raid members %.2f DKP in the %s pool for %s.", dkp, pool, notes), "RAID")
   end
   
   -- Set the database
   local ts = PandaDKPMaster:GetTimestamp()
   PandaDKPMaster.Events:InsertAwardEvent(ts, pool, dkp, notes, players)
   
   -- Send a message on guild to other officers
   local message = PandaDKPMaster.Messages:CreateAWMessage(ts, pool, dkp, notes, players)
   PandaDKPMaster.Comm:Send("GUILD", message)
   
   -- Send a message on guild to all users
   message = PandaDKPMaster.Messages:CreateAwardMessage(ts, pool, dkp, notes, players)
   PandaDKPMaster.Comm:SendClient("GUILD", message)
end


-- Called when an AW message is seen
function Awarding:OnAwardMessage(timestamp, pool, dkp, mob, players)
   -- MD5 the message
   local message = PandaDKPMaster.Messages:CreateAWMessage(timestamp, pool, dkp, mob, players)
   local md5 = PandaDKPMaster.MD5Lib:MD5(message)
   
   -- If we've already seen it, skip it
   if (nil ~= PandaDKPMaster.db.realm.DKP.Events[md5]) then return end
   
   -- Add the event
   PandaDKPMaster.Events:InsertAwardEvent(timestamp, pool, dkp, mob, players)
end












----------------------
--   Interface UI   --
----------------------

function Awarding:SetupUI()
   Awarding.UI.SelectedPool = PandaDKPMaster.db.realm.DKP.Pools[1]
   PDKPM_AwardingIncludeRaidCheck:SetChecked(Awarding.IncludeRaid)
   
   PDKPM_AwardingIncludePlayerMenuButton:SetScript("OnClick",
    function()
      PandaDKPMaster.Awarding:OnIncludePlayerMenuClick(PDKPM_AwardingIncludePlayerMenu)
      PlaySound("igMainMenuOptionCheckBoxOn");
	 end)
   PDKPM_AwardingPoolMenuButton:SetScript("OnClick",
    function()
      PandaDKPMaster.Awarding:OnPoolMenuClick(PDKPM_AwardingPoolMenu)
      PlaySound("igMainMenuOptionCheckBoxOn");
	 end)
   PDKPM_AwardingPoolMenuText:SetText(Awarding.UI.SelectedPool)
end

function Awarding:OnIncludeRaidClick()
end

function Awarding:OnIncludePlayerMenuClick(button)
   local options = { type = "group", args = {}, }
   local players = PandaDKPMaster.Players:AllPlayers()
   sort(players)
   
   for i, player in ipairs(players) do
      local class = PandaDKPMaster.Players:Class(player)
      local letter = strsub(player, 1, 1)
      if (nil == options.args[letter]) then
         local group = {
            type = 'group',
            name = letter,
            desc = letter,
            args = {},
            order = strbyte(letter),
         }
         options.args[letter] = group
      end
      
      local option =
      {
         type = 'toggle',
         name = string.format("|cff%s%s|r ", PandaDKPMaster:getClassHex(class), player),
         desc = player,
         set = function(player) Awarding:SelectPlayer(player) end,
         get = function(player) return Awarding:PlayerIsSelected(player) end,
         order = i,
         passValue = player,
      }
      tinsert(options.args[letter].args, option)
   end
   
   options.args["spacer"] = 
   {
      type = 'header',
      name = ' ',
      desc = ' ',
      order = 100,
   }
   
   options.args["clear_all"] = 
   {
      type = 'execute',
      name = 'Clear All',
      desc = 'Clear all players from the list (does not remove raid players)',
      func = function() Awarding.OtherPlayers = {} Awarding:RedisplayPlayerList() end,
      order = 105,
   }
   
   dewdrop:Open(button, 'children', options, 'point', "TOP", 'relativePoint', "BOTTOM")
end


function Awarding:OnIncludePlayerClick()
   local player = PDKPM_AwardingIncludePlayerEdit:GetText()
   if (nil == player or "" == player) then
      PandaDKPMaster:Print("You must enter a valid player name")
      return
   end
   Awarding:SelectPlayer(player)
end

function Awarding:OnPoolMenuClick(button)
   local options = { type = "group", args = {}, }
   for i, pool in ipairs(PandaDKPMaster.db.realm.DKP.Pools) do
      local option =
      {
         type = 'execute',
         name = pool,
         desc = pool,
         func = function(pool) Awarding:SelectPool(pool) dewdrop:Close(); end,
         order = i,
         passValue = pool,
      }
      tinsert(options.args, option)
   end
   dewdrop:Open(button, 'children', options, 'point', "TOP", 'relativePoint', "BOTTOM")
end

function Awarding:OnCreateAwardClick()
   local dkp = tonumber(PDKPM_AwardingAmountEdit:GetText())
   if (nil == dkp or (dkp > -0.01 and dkp < 0.01)) then
      PandaDKPMaster:Print("You must enter a non-zero DKP value")
      return
   end
   
   local pool = Awarding.UI.SelectedPool
   if (nil == pool or "" == pool) then
      PandaDKPMaster:Print("You must select a pool for the award.")
      return
   end
   
   local notes = tostring(PDKPM_AwardingDescriptionEdit:GetText())
   if (nil == notes or "" == notes) then
      PandaDKPMaster:Print("You must enter a description for the award.")
      return
   end
   
   Awarding:UpdateAwardList()
   local players = Awarding.AwardList
   if (nil == players or 0 == #players) then
      PandaDKPMaster:Print("You must select at least one player to award.")
      return
   end
   
   Awarding:ConfirmAward(dkp, pool, notes, players)
end




function Awarding:SelectPlayer(player)
   if (Awarding:PlayerIsSelected(player)) then
      Awarding.OtherPlayers[player] = false
   else
      Awarding.OtherPlayers[player] = true
   end
   Awarding:RedisplayPlayerList()
end

function Awarding:PlayerIsSelected(player)
   return Awarding.OtherPlayers[player]
end

function Awarding:RedisplayPlayerList()
   Awarding:UpdateAwardList()
   PDKPM_AwardingPlayersDesc:SetText(Awarding:ColorizedPlayerList(Awarding.AwardList))
end

function Awarding:SelectPool(pool)
   Awarding.UI.SelectedPool = pool
   PDKPM_AwardingPoolMenuText:SetText(Awarding.UI.SelectedPool)
end

function Awarding:ColorizedPlayerList(players)
   local hex
   local colorized = {}
   for _, player in ipairs(Awarding.AwardList) do
      hex = PandaDKPMaster:getClassHex(PandaDKPMaster.Players:Class(player))
      tinsert(colorized, string.format("|cff%s%s|r", hex, player))
   end
   
   return table.concat(colorized, ', ')
end



function Awarding:ConfirmAward(dkp, pool, notes, players)
   local data =
   {
      dkp = dkp,
      pool = pool,
      notes = notes,
      players = players,
   }
               
   StaticPopupDialogs["PDKPM_CONFIRM_AWARD"].text = 
    string.format("Award %0.2f DKP in %s to %s?", dkp, pool, Awarding:ColorizedPlayerList(Awarding.AwardList))
   StaticPopupDialogs["PDKPM_CONFIRM_AWARD"].UserData = data
    
   StaticPopupDialogs["PDKPM_CONFIRM_AWARD"].OnAccept = 
      function(dialog)
         local data = StaticPopupDialogs[dialog.which].UserData
         PandaDKPMaster.Awarding:CreateAwardConfirmed(data.dkp, data.pool, data.notes, data.players)
      end
                
   StaticPopup_Show("PDKPM_CONFIRM_AWARD")
end

StaticPopupDialogs["PDKPM_CONFIRM_AWARD"] = {
   text = "", -- will be assigned by creater
   button1 = "Yes",
   button2 = "No",
   OnAccept = nil, -- will be assigned by creater
   OnCancel = function() end,
   sound = "levelup2",
   timeout = 10,
   whileDead = 1,
   hideOnEscape = 1
}